package com.lkd.business;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MsgHandlerContextImpl implements ApplicationContextAware,MsgHandlerContext {


    private Map<String,MsgHandler> handlerMap = new HashMap<>();

    @Override
    public MsgHandler getMsgHandler(String topic) {
        return handlerMap.get(topic);
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {

//        获取当前容器中的MsgHandler的实现类 key-类的名字  value-ioc中的bean
        Map<String, MsgHandler> beans = ctx.getBeansOfType(MsgHandler.class);

        beans.values().stream().forEach(
                msgHandler -> {
                    String topic = msgHandler.getClass().getAnnotation(Topic.class).value();
                    handlerMap.put(topic,msgHandler);
                }
        );
    }
}
